//
//  ReleaseView.m
//  ECBBusinessCamp
//
//  Created by rimi on 16/6/21.
//  Copyright © 2016年 邓毕华. All rights reserved.
//

#import "ReleaseView.h"

#import "EmojiView.h"

#define LABEL_FONTSIZE 27

@interface ReleaseView()<UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, assign) ReleaseViewType selectType; // 发布类型
@property (nonatomic, strong) UILabel * titleLabel; // 主题
@property (nonatomic, strong) UILabel * effectiveDateLabel; // 有效日期
@property (nonatomic, strong) UILabel * dateIntervalLabel; // 至
@property (nonatomic, strong) UILabel * pictureLabel; // 尊享图片或者邀请人员
@property (nonatomic, strong) UILabel * contentLabel; // 内容
@property (nonatomic, strong) UIButton * sureButton; // 确认按钮
@property (nonatomic, strong) UIButton * cancelButton; // 取消按钮
@property (nonatomic, strong) UIButton * emojiButton; // 表情按钮
@property (nonatomic, strong) UIDatePicker * datePicker; // 日期拾取器
@property (nonatomic, strong) UIView * coverView; // 遮盖视图
@property (nonatomic, strong) UIAlertController * alertController; // 弹出框
@property (nonatomic, strong) UIImagePickerController * imagePickerController; // 图像拾取器
@property (nonatomic, strong) EmojiView * emojiView; // 表情视图
@property (nonatomic, strong) NSArray * emojiArray; // 表情数组

@end

@implementation ReleaseView

#pragma mark 🌷🌷🌷life cycle🌷🌷🌷
- (instancetype)initWithType:(ReleaseViewType)releaseType SelectIndex:(SelectBlock)selectIndex
{
    self = [super init];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        _selectType = releaseType;
        _selectBlock = selectIndex;
        self.layer.masksToBounds = YES;
        
        // 添加视图
        [self addSubview:self.titleTextField];
        [self addSubview:self.startDateTextField];
        [self addSubview:self.stopDateTextField];
        [self addSubview:self.contentTextView];
        [self addSubview:self.titleLabel];
        [self addSubview:self.effectiveDateLabel];
        [self addSubview:self.dateIntervalLabel];
        [self addSubview:self.pictureLabel];
        [self addSubview:self.contentLabel];
        [self addSubview:self.sureButton];
        [self addSubview:self.cancelButton];
        [self addSubview:self.emojiButton];
        
        // 自动布局
        [_titleTextField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.sizeOffset(CGSizeMake(SCREEN_WIDTH * 0.33, SCREEN_HEIGHT * 0.05));
            make.left.equalTo(_titleLabel.mas_right);
            make.centerY.equalTo(_titleLabel);
        }];
        [_startDateTextField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(_titleTextField).multipliedBy(0.45);
            make.height.equalTo(_titleTextField);
            make.left.equalTo(_titleTextField);
            make.centerY.equalTo(_effectiveDateLabel);
        }];
        [_stopDateTextField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(_titleTextField).multipliedBy(0.45);
            make.height.equalTo(_titleTextField);
            make.right.equalTo(_titleTextField);
            make.centerY.equalTo(_effectiveDateLabel);
        }];
        [_contentTextView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(_titleTextField);
            make.height.offset(SCREEN_HEIGHT * 0.12);
            make.left.equalTo(_contentLabel.mas_right);
            make.top.equalTo(_contentLabel);
        }];
        [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(SCREEN_HEIGHT * 0.08);
            make.left.offset(SCREEN_WIDTH * 0.05);
        }];
        [_effectiveDateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(SCREEN_HEIGHT * 0.17);
            make.centerX.equalTo(_titleLabel);
        }];
        [_dateIntervalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_effectiveDateLabel);
            make.centerX.equalTo(_titleTextField);
        }];
        [_pictureLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(SCREEN_HEIGHT * 0.26);
            make.centerX.equalTo(_titleLabel);
        }];
        [_contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(SCREEN_HEIGHT * 0.35);
            make.centerX.equalTo(_titleLabel);
        }];
        [_sureButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.sizeOffset(CGSizeMake(SCREEN_WIDTH * 0.1, SCREEN_WIDTH * 0.034));
            make.left.offset(SCREEN_WIDTH * 0.18);
            make.bottom.offset(SCREEN_HEIGHT * -0.05);
        }];
        [_cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.equalTo(_sureButton);
            make.right.offset(SCREEN_WIDTH * -0.18);
            make.centerY.equalTo(_sureButton);
        }];
        [_emojiButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(_contentTextView).multipliedBy(0.6);
            make.width.equalTo(_emojiButton.mas_height).multipliedBy(0.8);
            make.top.equalTo(_contentTextView);
            make.left.equalTo(_contentTextView.mas_right);
        }];
        
        // 根据发布类型添加不同的控件
        if (releaseType == STUDENTSENJOYABLE) {
            [self addSubview:self.imageView];
            
            [_imageView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.size.sizeOffset(CGSizeMake(SCREEN_WIDTH * 0.1, SCREEN_WIDTH * 0.07));
                make.centerY.equalTo(_pictureLabel);
                make.left.equalTo(_pictureLabel.mas_right);
            }];
        } else {
            [self addSubview:self.button1];
            [self addSubview:self.button2];
            [self addSubview:self.button3];
            [self addSubview:self.button4];
            
            [_button1 mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(_titleTextField);
                make.top.equalTo(_pictureLabel);
            }];
            [_button2 mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(_button1.mas_right).offset(20);
                make.centerY.equalTo(_button1);
            }];
            [_button3 mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(_button1);
                make.top.equalTo(_button1.mas_bottom).offset(10);
            }];
            [_button4 mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(_button3);
                make.left.equalTo(_button2);
            }];
        }
    }
    return self;
}

#pragma mark 🌷🌷🌷UITextFieldDelegate🌷🌷🌷
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    // 默认日期拾取器为今天
    _datePicker.date = [NSDate dateWithTimeIntervalSinceNow:0];
    // 添加遮盖视图
    [self addSubview:self.coverView];
    
    // 自动布局
    [_coverView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
    [_coverView removeFromSuperview];
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    textField.text = [dateFormatter stringFromDate:_datePicker.date];
}

#pragma mark 🌷🌷🌷UIImagePickerControllerDelegate🌷🌷🌷
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        if ([info[UIImagePickerControllerMediaType] isEqualToString:@"public.image"]) {
            //UIImagePickerControllerMediaType：用户选择的媒体类型，得到的是一个NSString得值，返回@"public.image"或者@"public.movie"，通过这个值我们就可以判断用户选取的是图片还是视频了。
            //UIImagePickerControllerOriginalImage：没有被编辑过的原始图像。
            //UIImagePickerControllerEditedImage：用户编辑过后的图像（allowsEditing属性设为YES，通过编辑的到的图像）。
            //UIImagePickerControllerCropRect：返回用户选择的图像区域，它作为一个NSRect数据类型返回。
            //UIImagePickerControllerReferenceURL：返回一个媒体类型的NSURL。
            UIImage *originalImage = info[UIImagePickerControllerOriginalImage];
            _imageView.image = originalImage;
        }
    }else {
        _imageView.image = info[UIImagePickerControllerEditedImage];
    }
    
    [self.imagePickerController dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark 🌷🌷🌷event response🌷🌷🌷
- (void)respondsToBtn:(UIButton *)sender {
    _selectBlock(sender.tag - 10);
}
- (void)tapToImageView {
    UIPopoverPresentationController * ppVc = self.alertController.popoverPresentationController;
    ppVc.sourceView = _imageView;
    ppVc.sourceRect = _imageView.bounds;
    ppVc.permittedArrowDirections = UIPopoverArrowDirectionLeft;
    // 获取到根控制器
    UIViewController * rootVc = (UIViewController *)self.nextResponder.nextResponder;
    [rootVc presentViewController:self.alertController animated:YES completion:nil];
}
- (void)respondsToSelecGrounpButton:(UIButton *)sender {
    sender.selected = !sender.selected;
}
- (void)respondsToEmojiInput {
    [_contentTextView resignFirstResponder];
    _contentTextView.inputView = _contentTextView.inputView ? nil : self.emojiView;
    [_contentTextView becomeFirstResponder];
}

#pragma mark 🌷🌷🌷getters and setters🌷🌷🌷
- (UITextField *)titleTextField {
    if (!_titleTextField) {
        _titleTextField = [[UITextField alloc] init];
        _titleTextField.borderStyle = UITextBorderStyleBezel;
        _titleTextField.font = [UIFont boldSystemFontOfSize:25];
    }
    return _titleTextField;
}
- (UITextField *)startDateTextField {
    if (!_startDateTextField) {
        _startDateTextField = [[UITextField alloc] init];
        _startDateTextField.font = [UIFont systemFontOfSize:18];
        _startDateTextField.borderStyle = UITextBorderStyleBezel;
        _startDateTextField.delegate = self;
        _startDateTextField.inputView = self.datePicker;
    }
    return _startDateTextField;
}
- (UITextField *)stopDateTextField {
    if (!_stopDateTextField) {
        _stopDateTextField = [[UITextField alloc] init];
        _stopDateTextField.font = [UIFont systemFontOfSize:18];
        _stopDateTextField.borderStyle = UITextBorderStyleBezel;
        _stopDateTextField.delegate = self;
        _stopDateTextField.inputView = self.datePicker;
    }
    return _stopDateTextField;
}
- (UIDatePicker *)datePicker {
    if (!_datePicker) {
        _datePicker = [[UIDatePicker alloc] init];
    }
    return _datePicker;
}
- (UIImageView *)imageView {
    if (!_imageView) {
        _imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"enjoy_添加图片.png"]];
        _imageView.userInteractionEnabled = YES;
        
        // 添加点击手势
        UITapGestureRecognizer * tapGR = [[UITapGestureRecognizer alloc] init];
        [tapGR addTarget:self action:@selector(tapToImageView)];
        [_imageView addGestureRecognizer:tapGR];
    }
    return _imageView;
}
- (UITextView *)contentTextView {
    if (!_contentTextView) {
        _contentTextView = [[UITextView alloc] init];
        _contentTextView.font = [UIFont systemFontOfSize:18];
        _contentTextView.layer.borderWidth = 1;
        _contentTextView.layer.borderColor = RGB_COLOR(143, 143, 143, 1).CGColor;
    }
    return _contentTextView;
}
- (UIButton *)button1 {
    if (!_button1) {
        _button1 = [UIButton buttonWithType:UIButtonTypeCustom];
        [_button1 setTitleColor:RGB_COLOR(67, 67, 67, 1) forState:UIControlStateNormal];
        [_button1 setTitle:@" 企业家全球领导力(GL)高端班" forState:UIControlStateNormal];
        [_button1 setImage:[UIImage imageNamed:@"interaction_group.png"] forState:UIControlStateNormal];
        [_button1 setImage:[UIImage imageNamed:@"interaction_group_s.png"] forState:UIControlStateSelected];
        [_button1 addTarget:self action:@selector(respondsToSelecGrounpButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _button1;
}
- (UIButton *)button2 {
    if (!_button2) {
        _button2 = [UIButton buttonWithType:UIButtonTypeCustom];
        [_button2 setTitleColor:RGB_COLOR(67, 67, 67, 1) forState:UIControlStateNormal];
        [_button2 setTitle:@" 中国新生代企业家研修班" forState:UIControlStateNormal];
        [_button2 setImage:[UIImage imageNamed:@"interaction_group.png"] forState:UIControlStateNormal];
        [_button2 setImage:[UIImage imageNamed:@"interaction_group_s.png"] forState:UIControlStateSelected];
        [_button2 addTarget:self action:@selector(respondsToSelecGrounpButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _button2;
}
- (UIButton *)button3 {
    if (!_button3) {
        _button3 = [UIButton buttonWithType:UIButtonTypeCustom];
        [_button3 setTitleColor:RGB_COLOR(67, 67, 67, 1) forState:UIControlStateNormal];
        [_button3 setTitle:@" 金融与资本运营深度精研班" forState:UIControlStateNormal];
        [_button3 setImage:[UIImage imageNamed:@"interaction_group.png"] forState:UIControlStateNormal];
        [_button3 setImage:[UIImage imageNamed:@"interaction_group_s.png"] forState:UIControlStateSelected];
        [_button3 addTarget:self action:@selector(respondsToSelecGrounpButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _button3;
}
- (UIButton *)button4 {
    if (!_button4) {
        _button4 = [UIButton buttonWithType:UIButtonTypeCustom];
        [_button4 setTitleColor:RGB_COLOR(67, 67, 67, 1) forState:UIControlStateNormal];
        [_button4 setTitle:@" 演员活动" forState:UIControlStateNormal];
        [_button4 setImage:[UIImage imageNamed:@"interaction_group.png"] forState:UIControlStateNormal];
        [_button4 setImage:[UIImage imageNamed:@"interaction_group_s.png"] forState:UIControlStateSelected];
        [_button4 addTarget:self action:@selector(respondsToSelecGrounpButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _button4;
}
- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.font = [UIFont systemFontOfSize:LABEL_FONTSIZE];
        _titleLabel.text = _selectType == STUDENTSENJOYABLE ? @"尊享主题：" : @"标        题：";
    }
    return _titleLabel;
}
- (UILabel *)effectiveDateLabel {
    if (!_effectiveDateLabel) {
        _effectiveDateLabel = [[UILabel alloc] init];
        _effectiveDateLabel.font = [UIFont systemFontOfSize:LABEL_FONTSIZE];
        _effectiveDateLabel.text = @"有效日期：";
    }
    return _effectiveDateLabel;
}
- (UILabel *)dateIntervalLabel {
    if (!_dateIntervalLabel) {
        _dateIntervalLabel = [[UILabel alloc] init];
        _dateIntervalLabel.font = [UIFont systemFontOfSize:LABEL_FONTSIZE];
        _dateIntervalLabel.text = @"至";
    }
    return _dateIntervalLabel;
}
- (UILabel *)pictureLabel {
    if (!_pictureLabel) {
        _pictureLabel = [[UILabel alloc] init];
        _pictureLabel.font = [UIFont systemFontOfSize:LABEL_FONTSIZE];
        _pictureLabel.text = _selectType == STUDENTSENJOYABLE ? @"尊享图片：" : @"邀请人员：";
    }
    return _pictureLabel;
}
- (UILabel *)contentLabel {
    if (!_contentLabel) {
        _contentLabel = [[UILabel alloc] init];
        _contentLabel.font = [UIFont systemFontOfSize:LABEL_FONTSIZE];
        _contentLabel.text = _selectType == STUDENTSENJOYABLE ? @"尊享信息：" : @"内        容：";
    }
    return _contentLabel;
}
- (UIButton *)sureButton {
    if (!_sureButton) {
        _sureButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_sureButton setTitle:@"确定" forState:UIControlStateNormal];
        [_sureButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        _sureButton.tag = 10;
        _sureButton.layer.cornerRadius = 10;
        _sureButton.layer.borderColor = [UIColor redColor].CGColor;
        _sureButton.layer.borderWidth = 1;
        [_sureButton addTarget:self action:@selector(respondsToBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sureButton;
}
- (UIButton *)cancelButton {
    if (!_cancelButton) {
        _cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_cancelButton setTitle:@"取消" forState:UIControlStateNormal];
        [_cancelButton setTitleColor:RGB_COLOR(191, 192, 191, 1) forState:UIControlStateNormal];
        _cancelButton.tag = 11;
        _cancelButton.layer.cornerRadius = 10;
        _cancelButton.layer.borderColor = RGB_COLOR(191, 192, 191, 1).CGColor;
        _cancelButton.layer.borderWidth = 1;
        [_cancelButton addTarget:self action:@selector(respondsToBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancelButton;
}
- (EmojiView *)emojiView {
    if (!_emojiView) {
        _emojiView = [[EmojiView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT * 0.33) selecEmojiIndexBlock:^(NSInteger index) {
            if (index == -1) {
                [_contentTextView deleteBackward];
            } else {
                _contentTextView.text = [NSString stringWithFormat:@"%@%@", _contentTextView.text, self.emojiArray[index]];
            }
        }];
    }
    return _emojiView;
}
- (UIButton *)emojiButton {
    if (!_emojiButton) {
        _emojiButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_emojiButton setImage:[UIImage imageNamed:@"face_input.png"] forState:UIControlStateNormal];
        [_emojiButton addTarget:self action:@selector(respondsToEmojiInput) forControlEvents:UIControlEventTouchUpInside];
    }
    return _emojiButton;
}
- (UIView *)coverView {
    if (!_coverView) {
        _coverView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    }
    return _coverView;
}
- (UIImagePickerController *)imagePickerController {
    if (!_imagePickerController) {
        _imagePickerController = [[UIImagePickerController alloc] init];
    }
    return _imagePickerController;
}
- (UIAlertController *)alertController {
    if (!_alertController) {
        _alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请选择图片来源" preferredStyle:UIAlertControllerStyleActionSheet];
        // 获取到根控制器
        UIViewController * rootVc = (UIViewController *)self.nextResponder.nextResponder;
        [_alertController addAction:[UIAlertAction actionWithTitle:@"从相册选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSArray * mediatypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
                self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
                self.imagePickerController.mediaTypes = @[mediatypes[0]];
                self.imagePickerController.delegate = self;
                self.imagePickerController.allowsEditing = YES;
                [rootVc presentViewController:self.imagePickerController animated:YES completion:nil];
            }
        }]];
        [_alertController addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //获取支持的媒体格式
            NSArray * mediatypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
            // 判断是否支持需要设置的sourceType
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                // 1、设置图片拾取器上的sourceType
                self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
                // 2、设置支持的媒体格式
                self.imagePickerController.mediaTypes = @[mediatypes[0]];
                // 3、是否进入编辑状态
                self.imagePickerController.allowsEditing = YES;
                // 4、设置代理
                self.imagePickerController.delegate = self;
                [rootVc presentViewController:self.imagePickerController animated:YES completion:nil];
            } else {
                UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"系统模拟器暂不能提供照相功能" preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
                [rootVc presentViewController:alert animated:YES completion:nil];
            }
        }]];
        [_alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    }
    return _alertController;
}
- (NSArray *)emojiArray {
    if (!_emojiArray) {
        _emojiArray = [Emoji allEmoji];
    }
    return _emojiArray;
}

@end
